package com.learn.sb.redis.lua;

import com.learn.sb.redis.config.RedisConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.ArrayList;
import java.util.List;


public class RedisLuaDemo {

	public static void main(String[] args) {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);
		RedisTemplate redisTemplate = ctx.getBean(RedisTemplate.class);

		RedisLuaDemo demo = new RedisLuaDemo();
		// demo.testLua(redisTemplate);
		demo.testLuaWithParms(redisTemplate, "a", "b", "11", "22");
		demo.testLuaWithParms(redisTemplate, "a", "b", "11", "11");
	}

	public void testLuaWithParms(RedisTemplate redisTemplate,
			String key1, String key2, String args1, String args2) {
		String lua =
				"redis.call('set', KEYS[1], ARGV[1]) \n" +
				"redis.call('set', KEYS[2], ARGV[2]) \n" +
				"local str1 = redis.call('get', KEYS[1]) \n" +
				"local str2 = redis.call('get', KEYS[2]) \n" +
				"if str1 == str2 then \n" +
				"return 1 \n" +
				"else \n" +
				"return 0 \n" +
				"end \n";
		System.out.println(lua);
		DefaultRedisScript<Long> redisScript = new DefaultRedisScript<Long>();
		redisScript.setScriptText(lua);
		redisScript.setResultType(Long.class);
		// 采用 String 序列化器
		RedisSerializer<String> stringRedisSerializer = redisTemplate.getStringSerializer();
		// 定义 key 参数
		List<String> keyList = new ArrayList<>();
		keyList.add(key1);
		keyList.add(key2);
		// 传递两个参数值，其中第一个序列化器是key的序列化器，第二个是参数的序列化
		Long res = (Long) redisTemplate.execute(redisScript, stringRedisSerializer, stringRedisSerializer, keyList, args1, args2);
		System.out.println(res);
	}

	public void testLua(RedisTemplate redisTemplate) {
		DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
		redisScript.setScriptText("return 'Hello CarloZ'");  // 设置脚本
		redisScript.setResultType(String.class);  // 定义返回类型，不定义Redis不会返回结果

		RedisSerializer<String> stringRedisSerializer = redisTemplate.getStringSerializer();
		String resStr = String.valueOf(redisTemplate.execute(redisScript, stringRedisSerializer, stringRedisSerializer, null));
		System.out.println("resStr = " + resStr);
	}

}
